package com.nf.mvc.mapping;

import com.nf.mvc.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 此类可以作为讲mvc框架的入门级HandlerMapping实现，并没有用在框架中，
 * getHandler方法设计返回的不是链，而是handler对象本身
 * 此类与{@link com.nf.mvc.adapter.RequestResponseAdapter}配合使用
 * <p>properties文件的内容格式如下：键是可以处理的地址前缀，值是handler方法所在的类
 * p=web.ProductController
 * s=web.StudentController
 * </p>
 */
public class PropertiesHandlerMapping implements HandlerMapping {
    public static final String MAPPING_CONFIG_FILE = "mappings.properties";
    private final Map<String, Method> mappings = new HashMap<>();

    public PropertiesHandlerMapping() {
        parseMappings();
    }

    private void parseMappings() {
        Properties properties = new Properties();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(MAPPING_CONFIG_FILE);
        try {
            properties.load(inputStream);


            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                String prefix = entry.getKey().toString();
                String className = entry.getValue().toString();

                Class<?> clz = Class.forName(className);

                Method[] methods = clz.getDeclaredMethods();
                for (Method method : methods) {
                    // /p/list;/p/edit
                    String url = "/" + prefix + "/" + method.getName();
                    mappings.put(url, method);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object getHandler(HttpServletRequest request) throws Exception {
        String url = request.getRequestURI();

        Method m = mappings.get(url);
        return m;
    }
}
